// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

const surveyService = require('../../surveyService.js')

const app = getApp()

Page({
  data: {
    currentPageIndex:0,
    currentQuestion:null,
    surveyData:null,
    questionList:null,
    loading:false,
    centerDialogVisible:false,
    beginAt:'',
    endAt:'',
    isDraft:0,
    extra:'',
    showReturnButton:'',
    targetId:'',
    id:''
  },
  onLoad: function (options) {
    //用户登录
    const username = app.globalData.username
    const password = app.globalData.password
    surveyService.userLoginService(username,password);
    console.log("option.id==",options.id)
    this.setData({
      id: options.id
    })
    this.load() // 加载问卷
    this.data.beginAt = this.formatDateTime(); //开始计时
    // 加载问卷
      // surveyService.loadSurverService("1102")
      // .then(data => {
      //   this.setData({
      //     surveyContent:data,
      //   })
      //   console.log(data)
      // })
      // .catch(error => {
      //   console.error('加载问卷服务失败',error)
      // });
  },

  btntap:function() {
    // console.log(this.data.surveyData.surveyName)
    // console.log(this.data.currentPageIndex)
    // console.log(this.data.surveyData)
    // console.log(this.data.currentQuestion.questionAndOptionsList)
    console.log(this.data.currentQuestion)
    // console.log(this.data.questionList)
  },
  handleRadioChange(e) {
    const optionIndex = e.currentTarget.dataset.optionIndex
    const optionId = e.currentTarget.dataset.optionId

    if (this.data.currentQuestion && this.data.currentQuestion.questionAndOptionsList) {
      this.setData({
        ['currentQuestion.questionAndOptionsList[' + optionIndex + '].selectedOptionId']: optionId
      })
      console.log(optionIndex)
      console.log(optionId)
    } else {
      console.error('invalid currentQuestion or currentQuestion.questionAndOptionlList')
    }
  },
  // methods:{
    closeWin: function() {  //点击关闭按钮后，关闭当前页面并跳转
      wx.redirectTo({
        url: '/pages/index/index',
      })
    },
    // 为数字添加前导零
    padZero: function(num) {
      return num < 10 ? '0' + num : num 
    },
    formatDateTime: function() {
      // 获取当前时间
      var date = new Date()
      //获取年，月，日，时，分，秒
      var year = date.getFullYear()
      var month = this.padZero(date.getMonth()+1)
      var day = this.padZero(date.getDate())
      var hour = this.padZero(date.getHours())
      var minute = this.padZero(date.getMinutes())
      var second = this.padZero(date.getSeconds())
      // 返回格式化后的日期时间字符串
      return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second
    },
    prevQuestion: function() {  //跳转到上一页
      if(this.data.currentPageIndex > 0) {
        const newcurrentPageIndex = this.data.currentPageIndex - 1
        const newcurrentQuestion = this.data.questionList[newcurrentPageIndex]
        this.setData({
          currentPageIndex : newcurrentPageIndex,
          currentQuestion : newcurrentQuestion    
        })
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 100
        })
      } else {
        console.log('No previous question available.')
      }
    },
    async nextQuestion() { //跳转到下一页
      if (this.allQuestionsAnsweredOnCurrentPage()) {
        console.log(this.data.currentQuestion)
        if (this.data.currentPageIndex < this.data.questionList.length - 1) {
          const newcurrentPageIndex = this.data.currentPageIndex + 1 
          const newcurrentQuestion = this.data.questionList[newcurrentPageIndex]
          // const newcurrentQuestion = JSON.parse(JSON.stringify(this.data.questionList[newcurrentPageIndex]))
          newcurrentQuestion.questionAndOptionsList.forEach(obj => {
            obj.selectedOptionId = null
          })
          this.setData({
            currentPageIndex : newcurrentPageIndex,
            currentQuestion : newcurrentQuestion
          });
          console.log(this.data.currentQuestion)
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 100
          })
          // let upDatecurrentQuestion = this.data.currentQuestion.map((obj) => {
          //   return {
          //     ...obj,
          //     selectedOptionId: null
          //   }
          // })
          // this.setData({
          //   currentQuestion: upDatecurrentQuestion
          // })
        } else {
          console.log('No next question available.')
        }
      } else {  //滚动到第一个未回答的题目
        wx.showToast({
          title: '请填写完所有的题目',
        });
        // this.scrollToFirstUnansweredQuestion()
      }
    },
    // async submit() {
    //   setTimeout(function() {
    //     wx.navigateTo({
    //       url: '../thanks/thanks',
    //     })
    //   },500)
    //   // 显示提交成功，0.5秒后跳转到感谢页面
    //   wx.showToast({  
    //     title: '提交成功',
    //   });
    // },
    async submit() {
      this.setData({
        centerDialogVisible: true
      })
    },
    async submit2() {
      try {

        // this.data.endAt = this.formatDateTime()
        this.setData({
          endAt: this.formatDateTime()
        })
        console.log('返回值为：',this.allQuestionsAnswered())
        if(!this.allQuestionsAnswered()) {  //确保所有问题都作答
          console.log(this.allQuestionsAnswered())
          wx.showToast({
            title: '请在提交前回答所有问题',
          })
          return;
        }
        // this.setData({
        //   centerDialogVisible: true
        // })
        //创建一个 userAnswers 对象
        else {
          const userAnswers = {}
          this.data.questionList.forEach((item) => {
            const questionId = item.id
            userAnswers[questionId] = []
            item.questionAndOptionsList.forEach((sub) => {
              if (
                sub.selectedOptionId !== null &&
                sub.selectedOptionId !== undefined
              ) {
                userAnswers[questionId].push({
                  questionId: sub.id,
                  optionId: sub.selectedOptionId
                })
              }
            })
          })
          // 这是需要提交的数据的总和
          const surveyData = {
            beginAt: this.data.beginAt,
            endAt: this.data.endAt,
            userAnswers: userAnswers,
            isDraft:this.data.isDraft,
            extra:this.data.extra,
            surveyId:this.data.surveyData.surveyId
          }
          console.log(surveyData)
          // 提交问卷数据
          const response = await surveyService.userAnswerService(surveyData)
          if (response.data && response.data.code === 200) {
            console.log(response)
            wx.showToast({
              title: '提交成功',
            })
            setTimeout(function(){
              wx.redirectTo({
                url:'../thanks/thanks.wxml'
              })
            },500)
          } else {
            console.log(response.data.msg)
            wx.showToast({
              title: response.data.msg || '提交失败',
            })
          }
        }
      } catch (error) {
        console.error('提交问卷失败',error)
        wx.showToast({
          title: '提交失败，请稍后重试',
        })
      }
    },
    async load() {  //加载问卷
      try {
        this.data.loading = true
        const response = await surveyService.loadSurverService(this.data.id)
        if (response.data && response.data.code === 200) {
          this.data.surveyData = response.data.data || {}
          console.log(this.data.surveyData)
          console.log(this.data.surveyData.surveyName)
          this.data.questionList = response.data.data.scaleInfoVOS|| []
          this.setData({
            surveyData: this.data.surveyData,
            questionList:this.data.questionList
          })
          if (this.data.questionList.length >= 0) {
            const newcurrentPageIndex = 0
            const newcurrentQuestion = this.data.questionList[newcurrentPageIndex]
            console.log(1,newcurrentQuestion)
            newcurrentQuestion.questionAndOptionsList.forEach(obj => {
              obj.selectedOptionId = null
            })
            this.setData({
              currentPageIndex: newcurrentPageIndex,
              currentQuestion: newcurrentQuestion
            })
          }
        } else if (response.data && response.data.code === 500) {
          this.data.showReturnButton = true
          console.log('问卷截止')
          this.setData({
            showReturnButton: this.data.showReturnButton
          })
        }
      } catch(error) {
        console.error('加载问卷数据失败',error)
        console.log('问卷截止')
        this.data.showReturnButton = true
        console.log(this.data.showReturnButton)
        this.setData({
          showReturnButton:this.data.showReturnButton
        })
      } finally {
        this.data.loading = false
        this.setData({
          loading: this.data.loading
        })
      }
    },
    allQuestionsAnsweredOnCurrentPage:function() {
      if (this.data.currentQuestion) {
        return this.data.currentQuestion.questionAndOptionsList.every(
          (option) => 
          option.selectedOptionId !== null &&
          option.selectedOptionId !== undefined
        )
      }
      return false
    },
    // 滑到第一个还没回答的问题
    // scrollToFirstUnansweredQuestion: function() {
    //   if(this.data.currentQuestion) {
    //     const unansweredQuestionIndex = this.data.currentQuestion.questionAndOptionsList.findIndex((option) => {
    //       option.selectedOptionId === null ||
    //       option.selectedOptionId === undefined
    //     });
    //     if(unansweredQuestionIndex >= 0 ) {
    //       const query = wx.createSelectorQuery().in(this);
    //       query
    //       .select(`.question_${unansweredQuestionIndex}`)
    //       .boundingClientRect()
    //       .exec(function(res) {
    //         if(res[0]) {
    //           const element = res[0]
    //           wx.pageScrollTo({
    //             scrollTop: element.top,
    //             duration: 300
    //           })
    //         }
    //       })
    //     }
    //   }
    // },
    // 看是否所有问题都已经作答
    // allQuestionsAnswered: function() {
    //   if (this.data.questionList&& this.data.currentPageIndex === this.data.questionList.length - 1) {
    //     return this.data.questionList.every((question) => {
    //       question.questionAndOptionsList.every(
    //         (option) => 
    //         option.selectedOptionId !== null &&
    //         option.selectedOptionId !== undefined
    //       )
    //     })
    //   }
    // }, 
    // 看是否所有问题都已经解答
    // allQuestionsAnswered: function() {
    //   if (this.data.currentQuestion && this.data.currentPageIndex === this.data.questionList.length - 1) {
    //     console.log(this.data.currentQuestion)
    //     console.log(this.data.currentPageIndex)
    //     console.log(this.data.questionList.length)
    //     this.data.currentQuestion.questionAndOptionsList.every((option,index) => {
    //       console.log(option.selectedOptionId)
    //       if (option.selectedOptionId === null ||
    //         option.selectedOptionId === undefined) {
    //           return false;
    //         }
    //     })
    //     return true;
    //   }
    // },
    //滑到当前页面第一个还没回答的问题
    scrollToFirstUnansweredQuestion: function() {
      for (let i = 0; i < this.data.currentQuestion.questionAndOptionsList.length; i++) {
        if (this.data.currentQuestion.questionAndOptionsList[i].selectedOptionId === null ||
          this.data.currentQuestion.questionAndOptionsList[i].selectedOptionId === undefined) {
            this.setData({
              targetId: this.data.targetId+ i
            })
            return
          }
      }
    },
    //看是否所有问题被回答
    allQuestionsAnswered:function() {
      if (this.data.currentPageIndex !== this.data.questionList.length - 1) {
        return false;
      }
      for (let i = 0; i < this.data.currentQuestion.questionAndOptionsList.length ; i++) {
        if (this.data.currentQuestion.questionAndOptionsList[i].selectedOptionId === null || 
          this.data.currentQuestion.questionAndOptionsList[i].selectedOptionId === undefined) {
            return false;
          }
      }
      return true;
    },
    //取消对话框
    handleDialogCancel:function() {
      this.setData({
        centerDialogVisible:false
      })
    }
  // },
});
